package com.cl.service;

import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.List;

import com.cl.dao.CommonDao;
import com.cl.dao.SearchDao;
import com.cl.util.CommonUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.cl.entity.UUser;
import com.cl.entity.UOrg;

import org.springframework.transaction.annotation.Transactional;

/**
 * 同步人员组织结构
 */
@Service
public class SinosoftUM {

    @Autowired
    private SearchDao<?> searchDao;

    @Autowired
    private CommonDao commonDao;

    @Value("#{applicationProperties['cas.umHome']}")
    protected String umHome;

    @Value("#{applicationProperties['cas.casHome']}")
    protected String casHome;

    @Value("#{applicationProperties['cas.baseDn']}")
    protected String baseDn;

    @Value("#{applicationProperties['cas.propertyURL']}")
    protected String propertyURL;

    @Autowired
    private CommonUtil commonUtil;

    /**
     *
     * @param url
     * @return
     */
    public static String getPersonFromURL(String url) {
        String s = null;
        BufferedReader r = null;
        try {
            URL u = new URL(url);
            URLConnection uc = u.openConnection();
            uc.setRequestProperty("Connection", "close");
            r = new BufferedReader(new InputStreamReader(uc.getInputStream(), "GBK"));
            StringBuffer buf = new StringBuffer();
            String line;
            while ((line = r.readLine()) != null) {
                buf.append(line);
            }
            s = buf.toString();
        } catch (Exception e) {
            System.out.println("读流出错：" + e);
        } finally {
            try {
                r.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    /**
     *
     * @param url
     * @return
     */
    private String getPropertyFromURL(String url) {
        String s = null;
        DataInputStream din = null;
        try {
            URL u = new URL(url);
            URLConnection uc = u.openConnection();
            uc.setRequestProperty("Connection", "close");
            din = new DataInputStream(uc.getInputStream());
            String temp = din.readUTF();
            if (temp != null) {
                if (!temp.equals("")) {
                    s = temp;
                }
            }
        } catch (Exception e) {

        } finally {
            try {
                if (din != null)
                    din.close();
            } catch (IOException ex) {

            }
        }
        return s;
    }

    /**
     * 获取院内的所有人
     * @return
     */
    public String getAllpersonfromLdap() {
        String userstr = null;
        String orgId = baseDn.replaceAll("=", "%3D");
        //String  urlstring = AvensConstants.UmHome + "queryldapbin1?objectclass=guGongPerson&basedn="+orgId+"&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&attrname=description";
        String urlstring = umHome
                + "queryldapbin1?objectclass=guGongPerson&basedn="
                + orgId
                + "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&attrname=description,mobilePhone,guGongTitle&personstatus=all";
        userstr = getPersonFromURL(urlstring);
        return userstr;
    }

    /**
     * 获取部门下的人员
     * @param orgID
     * @return
        */
    public String getpersonsfromLdapbyorg(String orgID) {
            String userstr = null;
            String orgId = "ou%3D" + orgID;
            String urlstring = umHome
                    + "queryldapbin1?objectclass=guGongPerson&basedn="
                    + orgId
                    + "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&attrname=description";
            userstr = getPersonFromURL(urlstring);
        return userstr;
    }

    private boolean isSame(String v1, String v2) {
        if (v1 == null)
            v1 = "";
        if (v2 == null)
            v2 = "";
        return v1.equals(v2);
    }

    @Transactional
    public String SyncUserOrgDataToDB() {
        String userstr = getAllpersonfromLdap();
        String[] sp = null;
        sp = userstr.split(";");
        int cout1 = 0;
        int cout2 = 0;
        Date dt = new Date();
        //同步用户信息
        for (int i = 0; i < sp.length; i++) {
            String[] uinf = new String[4];
            int lastPos = -1;
            int pos = -1;
            for (int j = 0; j < 4; j++) {
                lastPos = pos;
                pos = sp[i].indexOf(':', pos + 1);
                if (pos == -1) {
                    uinf[j] = sp[i].substring(lastPos + 1);
                    break;
                } else {
                    uinf[j] = sp[i].substring(lastPos + 1, pos);
                }
            }
            String userdn = uinf[0];
            int pos2 = userdn.indexOf(',');
            // 身份证号
            String userId;
            if (pos2 > 0)
                userId = userdn.substring(0, pos2);
            else
                userId = userdn;
            String name = uinf[1];
            String title = uinf[3];
            boolean bSave = true;
            UUser robj;
            try {
                // 获取人员信息
                robj = searchDao.getUserById(userId);
                if (isSame(name, robj.getName()) && isSame(userdn, robj.getUserdn()) && robj.getOrgId() != null) {
                    bSave = false;
                }
            } catch (Exception e) {
                // 新建一个对象
                robj = new UUser();
            }
            if (bSave) {
                robj.setName(name);
                robj.setUserId(userId);// 身份证号
                robj.setUserdn(userdn);// userdn
                robj.setCorp("故宫博物院");// 单位
                robj.setIdentificationUnit("院内");// 单位标识
                //c4w 避免初审选择,DTModify为NULL排序时会出现在TOP
                robj.setDtModify(dt);
                String org = "";
                int cpos = userdn.indexOf(',');
                if (cpos != -1)
                    org = userdn.substring(cpos + 1);
                robj.setOrgId(org);
                int ver = 1;
                Integer version = robj.getVersion();
                if (version != null)
                    ver = version ++;
                robj.setVersion(ver);
                commonDao.saveDBOject(robj);
                cout1 ++;
            }
        }
        int old_maxStatus = searchDao.getOrgMaxStatus();
        int new_maxStatus = old_maxStatus + 1;
        String orgstr = getAllDeptfromLdap();
        //同步组织机构信息
        sp = orgstr.split(";");
        for (int i = 0; i < sp.length; i++) {
            String[] sps = sp[i].split(":");
            String orgname = sps[1];
            String orgid = sps[0];
            String orgord = null;
            if (sps.length > 2)
                orgord = sps[2];
            int pos = orgid.indexOf(",");
            String oid = orgid;// 部门id
            String pid = orgid.substring(pos + 1);
            boolean bSave = true;
            UOrg robj;
            try {
                robj = searchDao.getOrgById(oid);
                String oldord = robj.getOrd() == null ? null : robj.getOrd().toString();
            } catch (Exception e) {
                robj = new UOrg();
            }
            if (bSave) {
                String orgName = orgname;
                robj.setOrgname(orgName);
                robj.setParentorgid(pid);
                robj.setOrgid(oid);
                int ord = 0;
                if (orgord != null && !orgord.equals("")) {
                    ord = Integer.parseInt(orgord);
                    robj.setOrd(ord);
                }
                int ver = 1;
                Integer version = robj.getVersion();
                if (version != null)
                    ver = version ++;
                robj.setVersion(ver);
                robj.setStatus(new_maxStatus);
                commonDao.saveDBOject(robj);
                cout2++;
            }
        }
        int count_to_del = searchDao.getOrgCountToDel(old_maxStatus);
        if (count_to_del > 0 && count_to_del < 100) {
            int num_del = commonDao.delOrgRecord(old_maxStatus);
        }
        // 更新部门科室
        List<UUser> users = searchDao.getInsideUser();
        for (UUser user:users) {
            String orgId = user.getOrgId();
            String orgName = commonUtil.getUserOrgNameByID(orgId);
            String officeName = commonUtil.getUserOfficeNameByID(orgId);
            user.setOrgName(orgName);
            user.setOfficeName(officeName);
            commonDao.saveDBOject(user);
        }
        return "更新人员：" + cout1 + "条，更新组织机构:" + cout2 + "条";
    }

    /**
     *
     * @param orgID
     * @param type type=zhengchuzhang 正处长 /type=zhengkezhang 正科长
     * @return
     */
    public String getDeptleaderfromLdap(String orgID, String type) {
        String orgid = "ou%3D" + orgID;
        String url = umHome
                + "getDutyPerson?condtype="
                + type
                + "&dn="
                + orgid
                + "&limitedorg="
                + orgid
                + "&condition=";
        //String urlstring = "http://192.168.1.213:8088/um/getDutyPerson?condtype=" + type + "&dn=" + orgid + "&limitedorg=" + orgid;
        String userstr = "";
        userstr = getPersonFromURL(url);
        return userstr;
    }

    /**
     * 获取所有部门信息
     * @return 所有部部门信息
     */
    public String getAllDeptfromLdap() {
        String orgId = baseDn.replaceAll("=", "%3D");
        String url = umHome
                + "queryldapbin1?objectclass=guGongDepartment&basedn="
                + orgId
                + "&scope=2&amensearch=ou%3D*&receivemode=1&dnsplit=;&attrname=description,guGongDepSerial";
        //String urlstring = "http://192.168.1.207:8088/um/queryldapbin1?objectclass=guGongDepartment&basedn=dc%3Dgugong&scope=1&amensearch=ou%3D*&receivemode=1&dnsplit=;&attrname=description";
        String orgstr = null;
        orgstr = getPersonFromURL(url);
        return orgstr;
    }

    /**
     *
     * @param userid
     * @return
     */
    public String getuserDnbyid(String userid) {
        userid = "cn%3D" + userid;
        String url = umHome
                + "queryldapbin?objectclass=guGongPerson&basedn="
                + baseDn
                + "&scope=2&amensearch="
                + userid
                + "&receivemode=1&dnsplit=;";
        //String urlstring = "http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn=" + orgId + "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
        String result = "";
        result = getPropertyFromURL(url);
        int i = result.indexOf(";");
        if (i > 0)
            result = result.substring(0, i);
        return result;
    }

    /**
     *
     * @param userdn
     * @return
     */
    public String getuserNamebyDn(String userdn) {
        String UserURL = userdn.replaceAll("=", "%3D");
        String urlstring = umHome
                + propertyURL
                + "?dn="
                + UserURL
                + "&attrlist=description&receivemode=1";
        String result = "";
        result = getPropertyFromURL(urlstring);
        return result;
    }

    /**
     * 根据组织DN获取某一组织结构下的所有人，并以String的形式表示
     * @param orgdn
     * @return
     */
    public String getResourceListStringFromLDAP(String orgdn) {
        //从LDAP中获取某一组织结构下的所有人，并以String的形式表示
        //queryldap?objectclass=guGongPerson&basedn=dc%3Dgugong&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;
        String orgId = orgdn.replaceAll("=", "%3D");
        String urlstring = umHome + "queryldapbin?objectclass=guGongPerson&basedn="
                + orgId
                + "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&jianzhi=1";
        //String urlstring = "http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn=" + orgId + "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
        String result = "";
        result = getPropertyFromURL(urlstring);
        return result;
    }

    /**
     *
     * @param orgid
     * @return
     */
    public String getorgDnbyid(String orgid) {
        String OrgId = "ou%3D" + orgid;
        String urlstring = umHome
                + "queryldapbin?objectclass=guGongDepartment&basedn="
                + baseDn
                + "&scope=2&amensearch="
                + OrgId
                + "&receivemode=1&dnsplit=;";
        //String urlstring = "http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn=" + orgId + "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
        String result = "";
            result = getPropertyFromURL(urlstring);
        int i = result.indexOf(";");
        if (i > 0)
            result = result.substring(0, i);
        return result;
    }

}